var express = require("express");
var router = express.Router();
var mysql = require("mysql");
var DateUtil = require('../lib/utils/DateUtil');
var _ = require("underscore");

var connection = require('../lib/utils/DbconnectUtil');

/**
 * 查询文章列表
 */
router.get('/:type', function (req, res, next) {
    var bannerType = req.params.type;
    var querySql = 'select * from t_banner where 1=1 and banner_type = ? limit 5';

    connection().query(querySql, [bannerType], function (error, rows) {
        if (error) {
            console.log(error);
            res.send({code: -1, message: 'query error'});
        } else {
            res.send({code: 0, data: rows});
        }
    });
});

router.put('/:type', function (req, res, next) {
    var sources = req.body;
    var bannerType = req.params.type;
    sources.banner_type = bannerType;
    var sqlStr = '';
    var param = [];
    if(!sources.id){
        sources.id =  new Date().getTime()+'';
        sqlStr = 'insert into t_banner set ?';
        param.push(sources);
    }
    else {
        sqlStr = 'update t_banner set ? where id = ?';
        param.push(sources);
        param.push(sources.id);
    }

    connection().query(sqlStr, param, function (error, rows) {
        if(!error){
            res.send({code: 0, message:'更新数据成功'});
        }
        else{
            res.send({code: -1, message:'更新数据失败'});
        }

    });

});


module.exports = router;